$NG.AllReady(function (
    page,
    { useDataIndexChange, useUpdateRow, useUpdateRows, useValuesChange, useClick }
) {
    // 编辑页面逻辑
    const mstform = $NG.getCmpApi("p_form_owner_rec_apply_m");
    const grid1 = $NG.getCmpApi("p_form_owner_rec_apply_d1");
    const grid2 = $NG.getCmpApi("p_form_owner_rec_apply_d2");
    const grid3 = $NG.getCmpApi("p_form_owner_rec_apply_d3");
    const grid4 = $NG.getCmpApi("p_form_owner_rec_apply_d4");

    // u_dept;
    var dtoolbar1 = $NG.getCmpApi("toolbar_p_form_owner_rec_apply_d1");
    dtoolbar1.insert({
        id: "add",
        text: "物料信息",
        iconCls: "icon-New",
    });
    useClick(async function ({ args }) {
        planadd();
    }, "add");
    function planadd() {
        $NG.external
            .openNGHelp({
                type: "NGMultipleHelp", //NGMultipleHelp
                helpId: "itemdataIdToNo", //帮助id
                valueField: "phid",
                labelField: "u_milestone_name", //显示字段
                // clientSqlFilter: {
                // 	bill_no: mstform.getValues().u_rkdbm_EXName,
                // 	phid_transno: 1,
                // },
            })
            .then((data) => {
                //根据字段名称新增引入每一行
                console.log(data, "data111111");
                try {
                    if (Array.isArray(data) && data.length > 0) {
                        var gridArr = [];
                        for (var i = 0; i < data.length; i++) {
                            console.log(data[i], "row1数据");
                            var gridObj = {};
                            //资源品类
                            gridObj.u_wl_no = data[i].origin.PhId;
                            gridObj.u_wl_no_EXName = data[i].origin.ItemNo;
                            gridObj.u_wl_name = data[i].origin.ItemName;
                            gridArr.push(gridObj);
                        }

                        console.log("planadd gridArr:");
                        console.log(gridArr);
                        grid1.addRows(gridArr);
                        grid1.refreshView();
                    } else {
                        console.error("返回的数据无效或为空:", data);
                    }
                } catch (error) {
                    console.error("处理数据时出错:", error);
                }
            })
            .catch((error) => {
                console.error("打开NGHelp时发生错误:", error);
            });
    }
    //表头字段变化逻辑BEGIN
    useValuesChange(({ args }) => {
        //监听来往单位名称
        console.log(args, "单位名称");

        //监听单位名称
        $NG.execServer(
            "fbsrdxx",
            { phid: args[0].u_unit_name.origin.phid },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas, "data11111s");

                if (datas.region_id) {
                    console.log(datas.region_id, "datas.region_id");
                    $NG.execServer("getAddressToId", { phid: datas.region_id }, function (res2) {
                        const data2 = JSON.parse(res2.data)[0].extendObjects; //单返回值
                        console.log(data2, "data2");
                        $NG.updateState((updater) => {
                            updater.data.p_form_owner_rec_apply_m.setProps({
                                u_nation: {
                                    value: data2.nationno,
                                    label: data2.nationname,
                                },
                                u_province: {
                                    value: data2.provinceno,
                                    label: data2.provincename,
                                },
                                u_city: {
                                    value: data2.cityno,
                                    label: data2.cityname,
                                },
                                u_region: {
                                    value: data2.regionno,
                                    label: data2.regionname,
                                },
                                u_xxdz:datas.detail_add
                            });
                        });
                    });
                }
                //功能扩展
                $NG.execServer(
                    "searchIDBank",
                    { phid: datas.taxbank_id },
                    function (res1) {
                        const data = JSON.parse(res1.data)[0].extendObjects; //单返回值
                        console.log(data, "data");
                        $NG.updateState((updater) => {
                            updater.data.p_form_owner_rec_apply_m.setProps({
                                u_swyh: {
                                    value: data.phid,
                                    label: data.bankno,
                                }, //税务银行行号11
                            });
                        });
                    }
                );

                $NG.updateState((updater) => {
                    updater.data.p_form_owner_rec_apply_m.setProps({
                        // u_contacts: datas.linkman, //联系人
                        // u_contacts_phone: datas.phone, //联系电话
                        // u_name1: datas.compname, //
                        u_unit_no: args[0].u_unit_name.origin.compno,
                        u_id_card: datas.iden_card_id, //法人身份证身份证
                        u_nssflx: datas.taxpayertype, //纳税身份类型11
                        u_nsr_name: datas.tax_person, //纳税人姓名11

                        u_swdjdz: datas.tax_register_addr, //税务地址名称11
                        u_swyhmc: datas.taxbank_name, //税务银行名称11
                        u_swdjh: datas.taxaccount_no, //税务登记账号11(税务登记账号)
                        u_swdjdh: datas.phone, //税务登记电话
                        u_tyshxydm: datas.three_to_one, //社会信用代码11(社会信用代码)
                        u_zcsj: datas.regdate, //成立日期11
                        u_rygm: datas.firm_size, //公司规模11
                        // u_yz_name: datas.psn, //法人11()
                        u_zczj: datas.reg_fund, //注册资本11
                    });
                });
                console.log(datas.taxbank_id, "datas.taxbank_id");
            }
        );
    }, "p_form_owner_rec_apply_m.u_unit_name");

    useValuesChange(({ args }) => {
        console.log(mstform.getValues().u_lx);
        if (mstform.getValues().u_lx == 2) {
            if (mstform.getValues().phid_pc) {
                return;
            }
            $NG.alert("请先选择工程项目");
            mstform.getItem("u_lx").setValue({ code: "", name: "" });
        }
    }, "p_form_owner_rec_apply_m.u_lx"); //表头选择u_region字段
    useValuesChange(({ args }) => {
        console.log(mstform.getValues().u_lx);
        $NG.execServer(
            "projectSjbm",
            { phid: mstform.getItem("phid_pc").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(res, "resprojectSjbm");
                $NG.updateState((updater) => {
                    updater.data.p_form_owner_rec_apply_m.setProps({
                        u_sj_no: datas.user_sjbm, //项目编码
                        u_sj_name: datas.user_sjmc, //项目名称
                    });
                });
                //searchYZTosjhsjbm
                if (datas.user_sjbm && datas.user_sjmc) {
                    //通过商机编码和名称查询业主名称
                    $NG.execServer(
                        "YZTosjhsjbm",
                        {
                            sjname: datas.user_sjmc,
                            sjno: datas.user_sjbm,
                        },
                        function (res) {
                            try {
                                let YZData = JSON.parse(res.data)[0].extendObjects;
                                console.log(YZData.u_yz_name, "YZData");
                                $NG.updateState((updater) => {
                                    updater.data.p_form_owner_rec_apply_m.setProps({
                                        u_yz_name: YZData.u_yz_name, //业主名称
                                    });
                                });
                            } catch (error) { }
                        }
                    );
                }
            }
        );

        if (mstform.getValues().u_lx == 2) {
            if (mstform.getValues().phid_pc) {
                return;
            }
            $NG.alert("请先选择工程项目");
            mstform.getItem("u_lx").setValue({ code: "", name: "" });
        }
    }, "p_form_owner_rec_apply_m.phid_pc"); //表头选择u_region字段

    useValuesChange(({ args }) => {
        console.log(args.value);
        mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
        mstform.getItem("u_city").setValue(""); //表头选择u_product_line字段
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_province"); //表头选择u_province字段
    useValuesChange(({ args }) => {
        mstform.getItem("u_region").setValue(""); //表头选择u_product_line字段
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_city"); //表头选择u_city字段
    useValuesChange(({ args }) => {
        console.log(args.value);
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_city.setProps({
                clientSqlFilter: { provinceno: mstform.getValues()?.u_province },
            });
            updater.fieldSetForm.p_form_owner_rec_apply_m.u_region.setProps({
                clientSqlFilter: { cityno: mstform.getValues()?.u_city },
            });
        });
    }, "p_form_owner_rec_apply_m.u_region"); //表头选择u_region字段



    useUpdateRows(({ args }) => {
        const rows = args[0];
        console.log(rows);
        if (mstform.getItem("u_sj_no").getValue() && mstform.getItem("u_dwsx").getValue()) {
            // if () {
            //     $NG.updateUI((updater, state) => {
            //         updater.fieldSetForm.p_form_visa_f_regist_d.u_cnt_name.setProps((e) => ({
            //             ...e,
            //             editor: {
            //                 ...e.editor,
            //                 required: true,
            //                 clientSqlFilter: {
            //                     phid_pc: `${mstform.getItem("phid_pc").getValue()}`,
            //                     bill_type: 1,
            //                 },
            //             },
            //         }));
            //     });
            // }
        } else {
            if (args[0].length > 0) {
                $NG.alert("请先补充商机号,推荐供应商");
                grid1.clearRows(); //先清空明细
            }
        }


        rows.forEach((row) => {
            //计算损失率
            row.u_ssl = (Number(((Number(row.u_vat_prc) || 0) -(Number(row.u_sc_prc) || 0)) / (Number(row.u_sc_prc) || 0)) || 0).toFixed(4)
            console.log(row.u_wl_name, "row");
            if (row.u_wl_no && mstform.getItem("u_sj_no").getValue() && mstform.getItem("u_dwsx").getValue()) {
                $NG.execServer(
                    "getHsdjToYztj",
                    {
                        '@sjbm': mstform.getItem("u_sj_no").getValue(),
                        '@itemno': row.u_wl_no,
                        '@dwmc': mstform.getItem("u_dwsx").getValue()
                    },
                    function (res) {
                        console.log(res, 'resgetHsdjToYztj')
                    }
                );

            }

            if (row.u_wl_name) {
                //功能扩展
                $NG.execServer(
                    "getItemdataphid",
                    { phid: row.u_wl_name },
                    function (res) {
                        const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        $NG.execServer(
                            "getItemdataByPhid",
                            { phid: data.phid_itemdata },
                            function (res) {
                                const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                                row.u_gg = datas.spec;
                                row.u_jldw = datas.msunit_name;
                                row.u_wl_no = datas.itemno;
                                console.log(datas); //物料小类
                                console.log(datas.phid_resbs); //物料小类
                            }
                        );
                    }
                );
                $NG.execServer("getResKSeach", { item_phid: row.u_wl_name }).then(
                    (res) => {
                        if (!res.data.length > 0) return; //判断是否有数据
                        const data = JSON.parse(res.data)[0].extendObjects; //单返回值
                        console.log(data.hsprc, "data.hsprc");
                        if (data.hsprc === 0) {
                            console.error("市场价格不能为 0，否则会导致除数为 0 的错误。");
                        } else {
                            row.u_sc_prc = data.hsprc;
                        }
                        let result = calculateLossRate(row.u_vat_prc, row.u_sc_prc);
                        console.log(result, "11111");
                        row.u_ssl = result;
                        grid1.refreshView();
                    },
                    (error) => {
                        console.log(error);
                    }
                );
            }
            // 根据物料编码带出信息
            if (row.u_wl_no_EXName) {
                $NG.execServer(
                    "getItemdataByNo",
                    { itemno: "'" + row.u_wl_no_EXName + "'" },
                    function (res) {
                        if (res.count > 0) {
                            let requestData = JSON.parse(res.data)[0].extendObjects; //单返回值
                            console.log(requestData, "获取请求值");
                            //物料名称
                            row.u_wl_name = requestData.itemname;
                            //物料编码
                            row.u_wl_no = requestData.phid;
                            row.u_wl_no_EXName = requestData.itemno;
                            //规格
                            row.u_gg = requestData.spec;
                            //计量单位
                            row.u_jldw = requestData.msunit_name;
                            // row.u_jldw = requestData.msunit_phid;
                            // row.u_jldw_EXName = requestData.msunit_name; //单位
                            //物料分类
                            row.u_product_type_mini = requestData.phid_resbs; //单位
                            row.u_product_type_mini_EXName = requestData.name; //单位
                            if (row.u_product_type_mini) {
                                $NG.execServer(
                                    "getAutoType",
                                    { phid: row.u_product_type_mini },
                                    function (res) {
                                        const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                                        row.u_item_sort = datas.f_phid;
                                        row.u_item_sort_EXName = datas.fname;
                                        row.u_product_type = datas.g_phid;
                                        row.u_product_type_EXName = datas.gname;
                                        row.u_product_type_mini = datas.phid_resbs;
                                        row.u_product_type_mini_EXName = datas.name;
                                        grid1.refreshView();
                                    }
                                );
                            }
                            grid1.refreshView();
                        } else {
                            console.log("useUpdateRows没有找到拟采购清单"); // items.u_u_pur_item = null; // items.u_u_pur_item_EXName = null;
                        }
                    }
                );
            }
            if (row.u_product_type_mini) {
                $NG.execServer(
                    "getAutoType",
                    { phid: row.u_product_type_mini },
                    function (res) {
                        const datas = JSON.parse(res.data)[0].extendObjects; //单返回值
                        row.u_item_sort = datas.f_phid;
                        row.u_item_sort_EXName = datas.fname;
                        row.u_product_type = datas.g_phid;
                        row.u_product_type_EXName = datas.gname;
                        row.u_product_type_mini = datas.phid_resbs;
                        row.u_product_type_mini_EXName = datas.name;
                        grid1.refreshView();
                    }
                );
            }
            grid1.refreshView()
        });
    }, "p_form_owner_rec_apply_d1");
    //页面条件
    if (page.oType == "add") {
        mstform.getItem("ng_insert_dt").setValue(new Date());
    }
});
function calculateLossRate(taxIncludedPrice = 0, marketPrice) {
    let lossRate =
        (Number(taxIncludedPrice) - Number(marketPrice)) / Number(marketPrice);
    return lossRate;
}
